package skeleton.android;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.List;
import android.app.*;
import android.app.ActivityManager.*;
import android.os.Bundle;
import android.os.Handler;
import android.view.ViewGroup.LayoutParams;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class Procesos extends Activity {
	
	Handler myHandler = new Handler();
	
	Thread thread = new Thread()
	{
	    @Override
	    public void run() {
	        try {
	            while(true) {
	                sleep(2000);
	                myHandler.post(finalAction);
	            }
	        } catch (InterruptedException e) {
	            e.printStackTrace();
	        }
	    }
	};
	
	Runnable finalAction = new Runnable() {
		
		public void run() {
			updateData();
		}
		
	};
	
	//TextView MessageText;
	TableLayout myTable;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
	    super.onCreate(savedInstanceState);
	    super.setTitle("Procesos Activos");	 
	    this.setContentView(R.layout.procesos);
	    
	    thread.start();
	    
	    
	}
	
	public void updateData() {
		
	    //MessageText = (TextView) findViewById(R.id.Title);
	    myTable = (TableLayout) findViewById(R.id.tableLayout1);
	    myTable.removeAllViews();
	    
	    ActivityManager taskInfo = (ActivityManager)this.getSystemService( ACTIVITY_SERVICE );	    
	    List<RunningAppProcessInfo> listP = taskInfo.getRunningAppProcesses(); 
	    
	    TableRow hd = new TableRow(this);
    	
    	TextView processNameH = new TextView(this);
    	processNameH.setText("PID");
    	hd.addView(processNameH);
		
		TextView processIDH = new TextView(this);
		processIDH.setText("ProcessName");
		hd.addView(processIDH);
		
		TextView processMemoryH = new TextView(this);
		processMemoryH.setText("CPU");
		hd.addView(processMemoryH);
		
		TextView processCPUH = new TextView(this);
		processCPUH.setText("Mem");
    	hd.addView(processCPUH);
		
		myTable.addView(hd, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		
		//proc stat
		long total_cpu = 0;
		double total_memory = 0;
		BufferedReader reader = null;
		String load = "";
		String[] toks = null;
		
		try 
		{
			reader = new BufferedReader( new InputStreamReader( new FileInputStream( "/proc/stat" ) ), 1000 );
		
			load = reader.readLine();
			reader.close();
		} 
		catch (FileNotFoundException e1) { e1.printStackTrace(); } 
		catch (IOException e) { e.printStackTrace(); }
		
		//System.out.println(load);
		
		toks = load.split(" ");
		
		for(int i=0; i < toks.length; i++)
		{
			if(toks[i].toString().equals("cpu"))
			{
				total_cpu = Integer.parseInt(toks[i + 2].toString()) + Integer.parseInt(toks[i + 3].toString()) + Integer.parseInt(toks[i + 4].toString());
				break;
			}
		}
		
		//memory
		try 
		{
			reader = new BufferedReader( new InputStreamReader( new FileInputStream( "/proc/meminfo" ) ), 1000 );
		
			load = reader.readLine();
			reader.close();
			
			toks = load.split(" ");
			
			//System.out.println("###Total memory: " + toks[9].toString());
			
			total_memory = Integer.parseInt(toks[9].toString());
		} 
		catch (FileNotFoundException e1) { e1.printStackTrace(); } 
		catch (IOException e) { e.printStackTrace(); }
		
		
		
		//proc pid stat
		double usage = 0;
		double memory = 0;
		DecimalFormat twoDForm = new DecimalFormat("#.##");
	    for(int i = 0; i < listP.size(); i++)
	    {
	    	TableRow tr = new TableRow(this);
	    	
	    	TextView ID = new TextView(this);
			ID.setText(""+listP.get(i).pid);
			tr.addView(ID);
	    	
	    	TextView processName = new TextView(this);
	    	processName.setText(listP.get(i).processName);
			tr.addView(processName);
			
			try
			{
				reader = new BufferedReader( new InputStreamReader( new FileInputStream( "/proc/"+listP.get(i).pid+"/stat" ) ), 1000 );
				
				load = reader.readLine();
				reader.close();
				toks = load.split(" ");
				
		        usage = 100.00 * ( Integer.parseInt(toks[13].toString()) + Integer.parseInt(toks[14].toString()) ) / (total_cpu*1.00);
			} 
	        catch (IOException e) { e.printStackTrace(); }
			
			TextView CPU = new TextView(this);
			CPU.setText(Double.valueOf(twoDForm.format(usage)) + "%");
	    	tr.addView(CPU);
	    	
	    	try
			{
				reader = new BufferedReader( new InputStreamReader( new FileInputStream( "/proc/"+listP.get(i).pid+"/statm" ) ), 1000 );
				
				load = reader.readLine();
				reader.close();
				toks = load.split(" ");
				
		        memory = 1.00 * ( Integer.parseInt(toks[0].toString()) / (1.00 * total_memory) );
			} 
	        catch (IOException e) { e.printStackTrace(); }
			
			TextView MEM = new TextView(this);
			MEM.setText(Double.valueOf(twoDForm.format(memory)) + "%");
	    	tr.addView(MEM);
	    	
			myTable.addView(tr, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
	    }
	}
}
